import React from 'react';

interface RadioGroupProps {
  value: string | undefined;
  onValueChange: (value: string) => void;
  children: React.ReactNode;
}

export function RadioGroup({ value, onValueChange, children }: RadioGroupProps) {
  console.log('RadioGroup 渲染:', { value, type: typeof value })
  
  // 递归处理子项，查找并处理RadioGroupItem
  const processChildren = (children: React.ReactNode): React.ReactNode => {
    return React.Children.map(children, child => {
      if (React.isValidElement(child)) {
        if (child.type === RadioGroupItem) {
          const childValue = child.props.value;
          const isChecked = childValue === value;
          console.log('RadioGroup 找到RadioGroupItem:', { childValue, isChecked, value })
          
          return React.cloneElement(child, { 
            checked: isChecked, 
            onChange: () => {
              console.log('RadioGroup 子项点击:', childValue)
              onValueChange(childValue)
            }
          } as any);
        } else if (child.props.children) {
          // 递归处理有children的元素
          return React.cloneElement(child, {
            children: processChildren(child.props.children)
          } as any);
        }
      }
      return child;
    });
  };
  
  return <div>{processChildren(children)}</div>;
}

interface RadioGroupItemProps extends React.InputHTMLAttributes<HTMLInputElement> {
  value: string;
  id?: string;
  checked?: boolean;
  onChange?: () => void;
}

export function RadioGroupItem({ value, id, checked, onChange, ...props }: RadioGroupItemProps) {
  return (
    <input
      type="radio"
      id={id || value}
      value={value}
      checked={checked}
      onChange={onChange}
      className="form-radio text-blue-600 focus:ring-blue-500 mr-2"
      {...props}
    />
  );
} 